package com.hundsun.cprs.yyt.web.action.trade;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.hundsun.cprs.yyt.service.trade.domain.TradeMatchDetail;
import com.hundsun.cprs.yyt.service.trade.service.TradeMatchService;
import com.hundsun.cprs.yyt.web.vo.excel.TradeEntrustAuditExportVo;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.TradeEntrustQuery;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustBSType;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustFrom;
import com.hundsun.cprs.yyt.service.trade.enums.EnumTradeEntrustStatus;
import com.hundsun.cprs.yyt.service.trade.enums.EnumTradeStatus;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.util.DateUtil;
import com.hundsun.cprs.yyt.util.DoubleUtil;
import com.hundsun.cprs.yyt.util.ExportExcelUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.util.ExportExcelWrapper;
import com.hundsun.cprs.yyt.web.vo.JsonModel;
import com.hundsun.cprs.yyt.web.vo.TradeEntrustVo;
import com.hundsun.cprs.yyt.web.vo.excel.TradeEntrustExportVo;

@Controller
@RequestMapping("/trade/entrust")
public class TradeEntrustAction extends BaseAction {
    
    @Autowired
    private TradeEntrustService tradeEntrustService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TradeMatchService tradeMatchService;
    
    @RequestMapping("/list")
    public void list(@ModelAttribute("query") TradeEntrustQuery query,ModelMap model){
        query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
        //query.setOrderStr("DESC");//降序排列
        //createTimeChans(query);
        defaultStatusSet(query);
        tradeEntrustService.selectByPage(query);
        model.put("tradeEntrustStatusMap", EnumTradeEntrustStatus.toMap());
        model.put("tradeStatusMap", EnumTradeStatus.toMap());
        model.put("entustFromMap",EnumEntustFrom.toStringMap());
    }
    
    @RequestMapping("/list_rollback")
    public void listRollback(@ModelAttribute("query") TradeEntrustQuery query,ModelMap model){
        query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
        query.setStatus(EnumTradeStatus.COMMITED.getStatus());
        tradeEntrustService.selectByPage(query);
        model.put("tradeEntrustStatusMap", EnumTradeEntrustStatus.toMap());
        model.put("tradeStatusMap", EnumTradeStatus.toMap());
        model.put("entustFromMap",EnumEntustFrom.toStringMap());
    }

    @RequestMapping("/audit/list")
    public void auditList(@ModelAttribute("query") TradeEntrustQuery query,ModelMap model){
        query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
        query.setStatus(EnumTradeStatus.INIT.getStatus());
        //createTimeChans(query);
        tradeEntrustService.selectAuditByPage(query);
        model.put("tradeEntrustStatusMap", EnumTradeEntrustStatus.toMap());
        model.put("tradeStatusMap", EnumTradeStatus.toMap());
        model.put("entustFromMap",EnumEntustFrom.toStringMap());
    }
    
    @RequestMapping(value = "/add",method=RequestMethod.GET)
    public void add(ModelMap model,@RequestParam(value = "goodsId",required = false)Long goodsId){
        TradeEntrust tradeEntrust = new TradeEntrust();
        tradeEntrust.setGoodsId(goodsId);
        model.put("data",tradeEntrust);
        GoodsInfo goods = goodsService.selectGoodsInfoById(goodsId.intValue());
        if (goods != null){
            model.put("goodsName",goods.getGoodsName());
        }
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(TradeEntrustVo entrust,ModelMap model) {
        try {
            Validate.notNull(entrust.getUserId(),"交易账户必填");
            Validate.notNull(entrust.getGoodsId(),"商品信息必填");
            Validate.notNull(entrust.getEntrustAmount(),"委托数量必填");
            Validate.notNull(entrust.getEntrustPrice(),"委托价格必填");
            Validate.notNull(entrust.getEntrustBs(),"委托方向必填");
            Validate.isTrue(entrust.getEntrustAmount() > 0,"委托数量必须大于0");
            Validate.isTrue(entrust.getEntrustPrice() >= 0,"委托价格必须大于等于0");
            UserAccountDTO user = remoteUserService.getUserDetailByUserId(entrust.getUserId());
            if (user == null || !user.isRealName()) {
                throw new IllegalArgumentException("交易账户未实名或不存在");
            }
            GoodsInfo goods = goodsService.selectGoodsInfoById(entrust.getGoodsId().intValue());
            if (goods == null) {
                throw new IllegalArgumentException("商品信息不存在");
            }
            TradeEntrust dbEntrust = new TradeEntrust();
            dbEntrust.setEntrustBs(entrust.getEntrustBs());
            dbEntrust.setEntrustPrice(new Double(DoubleUtil.mul(entrust.getEntrustPrice(), 100)).longValue());
            dbEntrust.setEntrustAmount(entrust.getEntrustAmount());
            dbEntrust.setUserId(user.getId());
            dbEntrust.setUserName(user.getName());
            dbEntrust.setFundAccount(user.getFundAccount());
            dbEntrust.setGoodsCode(goods.getGoodsCode());
            dbEntrust.setGoodsId(Long.valueOf(goods.getId()));
            dbEntrust.setEntrustFrom(EnumEntustFrom.FROM_PLATFORM.getCode());
            // 创建平台委售单
            tradeEntrustService.createEntrust(dbEntrust);
            // 平台委售单上报
            tradeEntrustService.entrust(dbEntrust);
            return success(model, "委售成功","/trade/entrust/list");
        } catch (IllegalArgumentException e) {
            return error(model,e.getMessage());
        } catch (Exception e) {
            log.error("委售失败",e);
            return error(model, "委售失败");
        }
    }

    @RequestMapping("/view")
    public void view(@RequestParam("entrustId")Long entrustId, String isShowBack,ModelMap model){
        TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustById(entrustId);
        tradeEntrust.setBusinessAmount(Math.abs(tradeEntrust.getBusinessAmount()));
        //填充交易对手方信息
        fillTradeMatchDetailInfo(tradeEntrust,model);
        model.put("data",tradeEntrust);
        model.put("tradeEntrustStatusMap", EnumTradeEntrustStatus.toMap());
        model.put("isShowBack",isShowBack);
    }

    public void fillTradeMatchDetailInfo(TradeEntrust tradeEntrust, ModelMap model){
        if (tradeEntrust != null){
            //查询交易对手方信息
            String bs = "";
            if (tradeEntrust.getEntrustBs().equals(EnumEntustBSType.SELL.getCode().toString())){
                bs = EnumEntustBSType.BUY.getCode().toString();
            }else{
                bs = EnumEntustBSType.SELL.getCode().toString();
            }
            List<TradeMatchDetail> tradeMatchDetailList = tradeMatchService.selectCounterpartyTradeMatchDetailListforView(tradeEntrust.getId(),bs);
            model.addAttribute("tradeMatchDetailList",tradeMatchDetailList);
        }
    }

    @RequestMapping("/audit.json")
    @ResponseBody
    public JsonModel audit(@RequestParam("result")String result){
        if (result==null){
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,"您未选择任何挂售单");
        }
        String[] entrustIds = result.split(",");
        try{
            tradeEntrustService.auditEntrust(entrustIds);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"挂售单审核成功");
        }catch (Exception e){
            log.error(e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,"挂售单审核失败");
        }
    }
    
    @RequestMapping("/export/excel")
    public void exportExcel(TradeEntrustQuery query, HttpServletResponse response) throws Exception {
        query.setPageSize(30000);
        query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
        //query.setOrderStr("DESC");//降序排列
        //createTimeChans(query);
        defaultStatusSet(query);
        tradeEntrustService.selectByPage(query);
        
        List<TradeEntrustExportVo> exportResult = new ArrayList<TradeEntrustExportVo>();
        for(TradeEntrust item : query.getData()){
            exportResult.add(new TradeEntrustExportVo(item));
        }
        
        String[] columnNames = { "委托序号", "关联订单编号","新老用户标签","用户名称","交易账号","商品编号","成本价","挂售数量","挂售状态","挂售时间","已售数量","已售金额","盈利金额","综合管理费","交易手续费","收入金额"};
        String fileName = "挂售数据导出";
        ExportExcelWrapper<TradeEntrustExportVo> util = new ExportExcelWrapper<TradeEntrustExportVo>();
        util.exportExcel(fileName, fileName, columnNames, exportResult, response, ExportExcelUtil.EXCEl_FILE_2007);
    }

    @RequestMapping("/audit/export/excel")
    public void exportAuditExcel(TradeEntrustQuery query, HttpServletResponse response) throws Exception {
        query.setPageSize(30000);
        query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
        query.setStatus(EnumTradeStatus.INIT.getStatus());
        //createTimeChans(query);
        tradeEntrustService.selectAuditByPage(query);

        List<TradeEntrustAuditExportVo> exportResult = new ArrayList<TradeEntrustAuditExportVo>();
        for(TradeEntrust item : query.getData()){
            exportResult.add(new TradeEntrustAuditExportVo(item));
        }

        String[] columnNames = { "委托序号","关联订单编号","新老用户标签", "用户名称","交易账号","商品编号","成本价","挂售数量","挂售状态","申请时间"};
        String fileName = "挂售审核数据导出";
        ExportExcelWrapper<TradeEntrustAuditExportVo> util = new ExportExcelWrapper<TradeEntrustAuditExportVo>();
        util.exportExcel(fileName, fileName, columnNames, exportResult, response, ExportExcelUtil.EXCEl_FILE_2007);
    }

    public void createTimeChans(TradeEntrustQuery query){
        if (query.getStartDate() == null){
            query.setStartDate(DateUtil.getBeginOfDay(new Date()));
        }
        if (query.getEndDate() == null){
            query.setEndDate(DateUtil.getEndOfDay(new Date()));
        }
    }
    
    @Override
    protected void initBinder(WebDataBinder binder) {
        // 注册默认的日期格式化类型: yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    public void defaultStatusSet(TradeEntrustQuery query){
        Integer[] defaultStatusArray = {2,3,4,5};
        if (query.getStatus()==null){
            query.setStatusArray(defaultStatusArray);
        }
    }
}
